// pages/login/login.js
const { login, postCode } = require('../../api/user')
Page({
  data: {
    background: '../../img/background.gif',
    user: '',
    pass: '',
    codeimg: ''
  },
  async formSubmit(e) {
    const formdata = e.detail.value
    const originCode = wx.getStorageSync('authCode')
    if (formdata.authCode != originCode) {
      wx.showToast({
        title: '验证码错误!',
        icon: 'error',
      })
      this.fetchCode()
      return
    }
    try{
      wx.showLoading({ title: '登录中' })
      const {authCode,...t} = formdata
      wx.setStorageSync('account', t.id)
      const res = await login(t)
      wx.setStorageSync('userInfo',JSON.stringify(res.data.user))
      wx.reLaunch({
        url: '../index/index/index',
      })
    }catch(e){
      console.log(e);
      wx.showToast({
        title: '登录失败',
      })
    }finally{
      wx.hideLoading()
    }
  },

  async fetchCode() {
    try {
      wx.removeStorageSync('authCode')
      const res = await postCode()
      const { authCode, img } = res
      wx.setStorageSync('authCode', authCode)
      this.setData({
        codeimg: img
      })
    } catch (e) {
      console.log(e);
      wx.showToast({
        title: '请求验证码失败',
      })
    }
  },
  //忘记密码
  forget() {
    wx.removeStorageSync('authCode')
    wx.navigateTo({
      url: '../forget/forget',
    })
  },
  //跳转注册
  register() {
    wx.removeStorageSync('authCode')
    wx.navigateTo({
      url: '../register/register',
    })
  },
  //加载页面
  onLoad() {
    // 监听窗口高度
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.windowHeight
        })
      },
    })
    //请求验证码
   this.fetchCode()
  },
  onShow(){
    const user = wx.getStorageSync('account')
    user && this.setData({
      user
    })
  },
  handleCodeClick(){
    this.fetchCode()
  }
})